package com.strato.repository.monitor.v1_0_0.timer;

public abstract class IntervalThread implements Runnable {

    private boolean active = false;

    private int interval = -1;

    private String name;

    private Thread runner;

    public IntervalThread(int intervalSeconds, String name) {
        this.interval = intervalSeconds * 1000;
        this.name = name;
    }

    public void start() {
        active = true;
        if (runner == null && interval > 0) {
            runner = new Thread(this);
            runner.start();
        }
    }

    public void stop() {
        active = false;
    }

    public void run() {
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        if(active){
        	if(interval<0){
        		doInterval();
        	}else{
        		 while (active) {
        			 try{
        				 doInterval();
        			 }catch (Exception e) {
        				 e.printStackTrace();
					}finally{
                         try {
                             Thread.sleep(interval);
                         } catch (InterruptedException e) {
                        	 e.printStackTrace();
                         }
        			 }
                 }
        	}
        }
    }

    public String toString() {
        return name;
    }

    protected abstract void doInterval();
}

